import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // 登录状态
  const isAuthenticated = ref(false)
  // 用户信息
  const user = ref(null)

  // 从本地存储加载登录状态
  const loadAuthState = () => {
    const savedAuth = localStorage.getItem('auth')
    if (savedAuth) {
      try {
        const authData = JSON.parse(savedAuth)
        isAuthenticated.value = authData.isAuthenticated || false
        user.value = authData.user || null
      } catch (e) {
        console.error('加载认证状态失败', e)
      }
    }
  }

  // 登录
  const login = async (username, password) => {
    try {
      // 调用登录API
      const response = await loginApi(username, password)
      
      // 保存token信息
      isAuthenticated.value = true
      user.value = {
        username: username,
        access_token: response.access_token,
        token_type: response.token_type || 'bearer',
        loginTime: new Date().toISOString()
      }
      
      // 保存到本地存储
      localStorage.setItem('auth', JSON.stringify({
        isAuthenticated: true,
        user: user.value
      }))
      
      return { success: true, message: '登录成功' }
    } catch (error) {
      // 错误信息已在request拦截器中处理，这里直接抛出
      throw error
    }
  }

  // 登出
  const logout = () => {
    isAuthenticated.value = false
    user.value = null
    localStorage.removeItem('auth')
  }

  // 初始化时加载认证状态
  loadAuthState()

  return {
    isAuthenticated,
    user,
    login,
    logout,
    loadAuthState
  }
})

